#include <Adafruit_AHTX0.h>
#include <PubSubClient.h>
#include <WiFi.h>
#include "DFRobot_BMP280.h"

#define SEA_LEVEL_PRESSURE    1015.0f   // sea level pressure

const char* ssid     ="一楼南";
const char* password ="Rivenqa1";
const char* MQTT_SERVER  = "81.70.170.122";
const int   MQTT_PORT    = 1883;//mqtt服务端口号
const char* TOPIC = "smarthome";//订阅主题
const char* client_id= "esp32c3_sensor_node";  //当前设备的clientid标志
long lastMsg = 0;
char data[30];
int flag=0;
WiFiClient espClient;
PubSubClient  client(espClient);
typedef DFRobot_BMP280_IIC  BMP;
BMP  bmp(&Wire, BMP::eSdoLow);
Adafruit_AHTX0  aht;

// show last sensor operate status
void printLastOperateStatus(BMP::eStatus_t eStatus)
{
  switch(eStatus) {
  case BMP::eStatusOK:    Serial.println("everything ok"); break;
  case BMP::eStatusErr:   Serial.println("unknow error"); break;
  case BMP::eStatusErrDeviceNotDetected:    Serial.println("device not detected"); break;
  case BMP::eStatusErrParameter:    Serial.println("parameter error"); break;
  default: Serial.println("unknow status"); break;
  }
}

void setup() {
  // put your setup code here, to run once:
   	Serial.begin(115200);//设置串行监听端口
    delay(10);//等待10毫秒
    Serial.println();
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);

    WiFi.begin(ssid, password);//连接wifi
	
	//等待wifi连接完成
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
    if(bmp.begin() != BMP::eStatusOK) {
    Serial.println("bmp begin faild");
    printLastOperateStatus(bmp.lastOperateStatus);
    delay(2000);
    }
    if (! aht.begin()) {
        Serial.println("Could not find AHT? Check wiring");
        while (1) delay(10);
      }

    client.setServer(MQTT_SERVER, MQTT_PORT); //设定MQTT服务器与使用的端口，1883是默认的MQTT端口
    client.setCallback(callback);        //设定回调方式，当ESP8266收到订阅消息时会调用此方法
}
void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect(client_id)) {
      Serial.println("connected");
      // 连接成功时订阅主题
      client.subscribe(TOPIC);
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);   // 打印主题信息
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]); // 打印主题内容
  }
  Serial.println();
}
void loop() {
  // put your main code here, to run repeatedly:
    if (!client.connected()) {
      reconnect();
    }
      sensors_event_t humidity, temp;
      aht.getEvent(&humidity, &temp);// populate temp and humidity objects with fresh data
      //Serial.println("========  aht10--data  ========");
      //Serial.print("Temperature: "); Serial.print(temp.temperature); Serial.println(" degrees C");
      //Serial.print("Humidity: "); Serial.print(humidity.relative_humidity); Serial.println("% rH");
      //Serial.println("========  aht10--data  ========");
  float   temp1 = bmp.getTemperature();
  uint32_t   press = bmp.getPressure();

      //Serial.println();
      //Serial.println("======== bmp280--data ========");
      //Serial.print("temperature (unit Celsius): "); Serial.println(temp1);
      //Serial.print("pressure (unit pa):         "); Serial.println(press);
      //Serial.println("========  bmp280--data  ========");
    if(flag>10){
          flag=0;
          Serial.println("------------发布消息------------");
          sprintf(data,"%.2f,%.2f,%.2f,%d",temp.temperature,humidity.relative_humidity,temp1,press);
          delay(50);
          client.publish(TOPIC,data);
    }
    delay(1000);
    flag++;
    client.loop();
}
